package org.kfish.framework.helper;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.protocol.RequestContent;
import org.kfish.framework.bean.FormParam;
import org.kfish.framework.bean.Param;
import org.kfish.framework.util.ArrayUtil;
import org.kfish.framework.util.CodecUtil;
import org.kfish.framework.util.StreamUtil;
import org.kfish.framework.util.StringUtil;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import ch.qos.logback.core.util.ContentTypeUtil;

public class RequestHelper {

	/**
	 * 将parameters 和 InputStream 所有的 内容整合到Param 对象中
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	public static Param createParam(HttpServletRequest request) throws IOException{
		List<FormParam> formParamList = new ArrayList<>();
		formParamList.addAll(parseParameters(request));
		formParamList.addAll(parseInputStream(request));
		
		return new Param(formParamList);
		
	}
	
	private static List<FormParam> parseParameters(HttpServletRequest request){
		List<FormParam> formParamList  = new ArrayList<>();
		Enumeration<String> paramNames = request.getParameterNames();
		while(paramNames.hasMoreElements()){
			String fieldName = paramNames.nextElement();
			String[] fieldValues = request.getParameterValues(fieldName);
			if(ArrayUtil.isNotEmpty(fieldValues)){
				Object fieldValue;
				if(fieldValues.length==1){
					fieldValue = fieldValues[0];
				}else{
					StringBuilder sb = new StringBuilder();
					for(int i = 0;i<fieldValues.length;i++){
						sb.append(fieldValues[i]);
						if(i<fieldValues.length-1){
							sb.append(StringUtil.SEPARATOR);
						}	
					}
					fieldValue = sb.toString();
				}
				formParamList.add(new FormParam(fieldName,fieldValue));
			}
		}
		return formParamList;	
	}
	
	//处理post请求中，不是以formData形式传递的
	private static List<FormParam> parseInputStream(HttpServletRequest request) throws IOException{
		List<FormParam> formParamList = new ArrayList<>();
		String body = CodecUtil.decodeURL(StreamUtil.getString(request.getInputStream()));
	
		
		if(StringUtil.isNotEmpty(body)){
			String contentType = request.getContentType();
			if(contentType.equals("application/json")){
				JsonParser jsonParser = new JsonParser();
				JsonElement jsonElement =jsonParser.parse(body);
				formParamList.add(new FormParam("json", jsonElement));		
			}else{
				formParamList.add(new FormParam("raw", body));
			}
			
		}
		return formParamList;
	}
	
}
